package com.tjetc.controller;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/file")
public class FileController {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket}")
    private String bucket;

    @Value("${minio.endpoint}")
    private String endpoint;

    @PostMapping("/upload")
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file) {
        System.out.println("开始上传文件...");
        Map<String, Object> result = new HashMap<>();
        try {
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            minioClient.putObject(
                PutObjectArgs.builder()
                    .bucket(bucket)
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build()
            );
            String url = endpoint + "/" + bucket + "/" + fileName;
            result.put("code", "200" +
                    "");
            result.put("msg", "上传成功");
            result.put("data", url);
        } catch (Exception e) {
            result.put("code", "500");
            result.put("msg", "上传失败: " + e.getMessage());
            result.put("data", null);
        }
        return result;
    }
} 